<template>
	<el-dialog width="99%" :close-on-click-modal="false" v-model="dialogVisible" :title="state.title" destroy-on-close :before-close="handleClose">
		<el-form ref="inboundRef" :model="state.form" :rules="state.rules">
			<el-table
				ref="dataTableRef"
				row-key="id"
				:tree-props="{ children: 'inboundItems' }"
				:span-method="arraySpanMethod"
				min-height="50vh"
				:header-cell-style="{ color: '#000' }"
				:row-class-name="tableRowClassName"
				:default-expand-all="true"
				border
				:data="state.form.infoData"
			>
				<!-- <el-table-column label="" width="30px" fixed="left" /> -->
				<el-table-column label="备货平台" prop="stockupPlatformName" min-width="120px">
					<template v-slot="scope">
						<el-descriptions v-if="scope.row.inboundItems" :column="4">
							<el-descriptions-item>
								{{ scope.row.inboundOrderCode }}
							</el-descriptions-item>
							<el-descriptions-item label="收获仓：">
								{{ scope.row.whNameTo }}
							</el-descriptions-item>
							<el-descriptions-item label="公司主体：">
								{{ scope.row.companyName }}
							</el-descriptions-item>
							<el-descriptions-item label="团队：">
								{{ scope.row.teamName }}
							</el-descriptions-item>
							<el-descriptions-item label="备货区域">
								{{ scope.row.stockupAreaName }}
							</el-descriptions-item>
							<el-descriptions-item label="业务类型：">
								<span v-for="item in inbound_bus_type" :key="item.id" v-show="Number(item.value) === Number(scope.row.busType)">
									{{ item.label }}
								</span>
							</el-descriptions-item>
						</el-descriptions>
						<span v-else>
							{{ scope.row.stockupPlatformName }}
						</span>
					</template>
				</el-table-column>
				<el-table-column label="产品图片" prop="picUrl" min-width="90px">
					<template v-slot="scope">
						<ewt-image v-if="scope.row.skuCode" :url="scope.row.picUrl" style="width: 36px; height: 36px; object-fit: contain" />
					</template>
				</el-table-column>
				<el-table-column label="产品名称/SKU" prop="companyName" min-width="140px">
					<template v-slot="scope">
						<template v-if="scope.row.skuCode">
							{{ scope.row.skuName }}<br /><br />
							{{ scope.row.skuCode }}
						</template>
					</template>
				</el-table-column>
				<el-table-column label="MSKU/FNSKU" prop="companyName" min-width="120px">
					<template v-slot="scope">
						<template v-if="scope.row.skuCode">
							{{ scope.row.mskuCode || '-' }}<br /><br />
							{{ scope.row.fnsku }}
						</template>
					</template>
				</el-table-column>
				<el-table-column label="应收数量" prop="supposeReceiveQty" min-width="100px"></el-table-column>
				<el-table-column label="产品质量" prop="supposeReceiveQty" min-width="100px">
					<template v-slot="scope">
						{{ scope.row.qualityType === '1' ? '良品' : scope.row.qualityType === '2' ? '次品' : scope.row.qualityType === '3' ? '废品' : '' }}
					</template>
				</el-table-column>
				<el-table-column label="实收数量" prop="qty" min-width="100px" fixed="right"> </el-table-column>
				<el-table-column label="入库库位" prop="" min-width="150px" fixed="right">
					<template #header>
						<span class="table-require">入库库位</span>
					</template>
					<template v-slot="scope">
						<div v-for="(item, ind) in scope.row.positionDTOS" :key="ind" class="add-pick">
							<div style="width: 40px; text-align: right">
								<el-icon style="margin-right: 6px" v-if="scope.row.positionDTOS.length > 1" @click="scope.row.positionDTOS.splice(ind, 1)">
									<Minus />
								</el-icon>
								<el-icon v-if="ind === scope.row.positionDTOS.length - 1" @click="scope.row.positionDTOS.push({ inboundQty: 0 })"><Plus /></el-icon>
							</div>
							<el-form-item
								label=""
								:prop="'infoData.' + getPropPosi(scope.row) + '.positionDTOS.' + ind + '.positionId'"
								:rules="state.rules.positionId"
							>
								<el-cascader
									class="only-form"
									v-model="item.position"
									:options="scope.row.seatList"
									placeholder="入库库位"
									filterable
									:props="{ value: 'code', label: 'code', children: 'children' }"
									:show-all-levels="false"
									@focus="judgeCanCheckPositions(scope.row)"
									@change="changePosition(scope.row, item)"
								/>
							</el-form-item>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="入库数量" prop="" min-width="160px" fixed="right">
					<template #header>
						<span class="table-require">入库数量</span>
						<el-text type="primary" style="cursor: pointer" @click="toInputQty">一键填入</el-text>
					</template>
					<template v-slot="scope">
						<div v-for="(item, ind) in scope.row.positionDTOS" :key="ind" class="add-pick">
							<el-input
								v-model="item.inboundQty"
								placeholder="入库数量"
								oninput="value=value.replace(/^\D*(\d{0,9}(?:)?).*$/g,'$1')"
								@blur="item.inboundQty = Number($event.target.value)"
							></el-input>
						</div>
					</template>
				</el-table-column>
			</el-table>
		</el-form>

		<template #footer>
			<el-button type="" @click="handleClose">取消</el-button>
			<el-button type="primary" class="ml10" @click="toSaveInbound">完成入货</el-button>
		</template>
	</el-dialog>
</template>
<script lang="ts" setup  name="inboundDialog">
import { ElMessage } from 'element-plus';
import { useDict } from '/@/hooks/dict';
const { inbound_bus_type } = useDict('inbound_bus_type');
import { showInboundDetail, completeInbound } from '../api.ts';
const state = reactive({
	title: '入货',
	form: {
		infoData: [],
	},

	rules: {
		positionId: [{ required: true, message: '', trigger: ['blur', 'change'] }],
	},
});
const dialogVisible = ref(false);
const dataTableRef = ref();
const inboundRef = ref();
const emit = defineEmits(['refresh']);
const getPropPosi = (row) => {
	let posi = findPosi(state.form.infoData, row, '', '');
	return posi;
};
const findPosi = (list, row, posi, current) => {
	for (let i = 0; i < list.length; i++) {
		if (list[i].id == row.id) {
			return current + i;
		}
		if (list[i].inboundItems && list[i].inboundItems?.length) {
			posi = findPosi(list[i].inboundItems || [], row, posi, i + posi + '.inboundItems.');
		}
	}
	return posi;
};

// 打开弹窗
const openDialog = async (list) => {
	state.form.infoData = JSON.parse(JSON.stringify(list));
	let arr = [];
	state.form.infoData.forEach((item) => {
		item.itemList.forEach((it) => {
			let obj = {
				itemId: it.id,
				skuId: it.skuId,
				whId: item.whIdTo,
			};
			arr.push(obj);
		});
	});
	showInboundDetail(arr).then((res) => {
		state.form.infoData.forEach((item) => {
			item.inboundItems = [];
			item.itemList.forEach((it, itInd) => {
				it.productItems = res.data.find((i) => {
					if (i.itemId === it.id) {
						i.productItems.map((j, n) => {
							if (n === 0) {
								j.stockupPlatformName = it.stockupPlatformName;
								j.picUrl = it.picUrl;
								j.skuName = it.skuName;
								j.skuCode = it.skuCode;
								j.mskuCode = it.mskuCode;
								j.fnsku = it.fnsku;
								j.supposeReceiveQty = it.supposeReceiveQty;
							}
							j.inboundOrderId = item.id;
							j.positionDTOS = [
								{
									positionId: '',
									positionCode: '',
									inboundQty: 0,
								},
							];
							j.qty = j.qualityType === '1' ? j.goodQty : j.qualityType === '2' ? j.defectiveQty : j.qualityType === '3' ? j.scrapQty : 0;
							j.seatList = [];

							j.positions.forEach((ele) => {
								let obj2 = {
									code: ele.areaCode,
									id: ele.id,
									children: [],
								};
								ele.positions.forEach((m) => {
									obj2.children.push({
										code: m.positionCode,
										id: m.positionId,
									});
								});
								j.seatList.push(obj2);
							});

							item.inboundItems.push(j);
						});
					}
				});
			});
		});
	});

	dialogVisible.value = true;
};
// 关闭弹窗
const handleClose = () => {
	dialogVisible.value = false;
};
const toInputQty = () => {
	state.form.infoData.forEach((item) => {
		item.inboundItems.map((i) => {
			let obj = JSON.parse(JSON.stringify(i.positionDTOS[0]));
			i.positionDTOS = [
				{
					positionId: obj.positionId,
					positionCode: obj.positionCode,
					position: obj.position,
					inboundQty: i.qty,
				},
			];
		});
	});
};
const changePosition = (row, item) => {
	if (item.position?.length > 0) {
		item.positionCode = item.position[1];
		row.seatList.forEach((i) => {
			i.children.find((it) => {
				if (it.code === item.positionCode) {
					item.positionId = it.id;
				}
			});
		});
	}
};
const judgeCanCheckPositions = (row) => {
	let arr = row.positionDTOS.map((item) => {
		return item.positionId;
	});
	row.seatList.forEach((i) => {
		i.children.find((it) => {
			if (arr.indexOf(it.id) !== -1) {
				it.disabled = true;
			} else {
				it.disabled = false;
			}
		});
	});
};
const tableRowClassName = ({ row, rowIndex }) => {
	if (row.inboundItems) {
		return 'row-header';
	}
	return '';
};
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
	if (row.inboundItems) {
		if (columnIndex === 0) {
			return [1, 6];
		} else if (columnIndex > 0 && columnIndex < 6) {
			return [0, 0];
		} else {
			return [1, 1];
		}
	}
};
const toSaveInbound = () => {
	inboundRef.value.validate((v) => {
		if (v) {
			let msg = null;
			state.form.infoData.forEach((item) => {
				item.inboundItems.map((i) => {
					var sum = i.positionDTOS.reduce(function (acc, obj) {
						return acc + obj.inboundQty;
					}, 0);
					if (sum !== i.qty) {
						msg = '入库数量需等于实收数量';
					}
				});
			});
			if (msg) {
				ElMessage({
					message: msg,
					type: 'error',
				});
			} else {
				let data = [];
				state.form.infoData.map((item) => {
					data = [...data, ...item.inboundItems];
				});
				completeInbound(data)
					.then((res) => {
						ElMessage({
							message: res.msg || '入库成功',
							type: 'success',
						});
						handleClose();
						emit('refresh');
					})
					.catch((res) => {
						ElMessage({
							message: res.msg,
							type: 'error',
						});
					});
			}
		}
	});
};
defineExpose({
	openDialog,
});
onMounted(() => {});
</script>
<style scoped>
:deep(.el-table .row-header td) {
	background-color: #f5f7fa !important;
}
.table-require::before {
	content: '*';
	color: #e52e2e;
	margin-right: 4px;
}
:deep(.el-table [class*='el-table__row--level'] .el-table__expand-icon) {
	display: none;
}
.add-pick {
	display: flex;
	align-items: center;
	gap: 6px;
	margin: 6px 0;
}
.add-pick :deep(.el-form-item) {
	width: calc(100% - 40px) !important;
}
.add-pick i {
	cursor: pointer;
}
</style>
